import { storeToRefs } from "pinia";
import { getScreenSize } from "@/utils";
import { globalScale } from "@/config/static";
import { useMapStore } from "@/store/mapStore";
import { useUserStore } from "@/store/userStore";
import { useTimeStore } from "@/store/timeStore";

interface RainDrop {
  x: number; // 雨滴的 x 坐标
  y: number; // 雨滴的 y 坐标
  length: number; // 雨滴的长度
  speed: number; // 雨滴的下落速度
  opacity: number; // 雨滴的透明度
}

// 添加溅落效果接口
interface SplashDrop {
  x: number;
  y: number;
  radius: number; // 溅落的半径
  maxRadius: number; // 溅落的最大半径
  opacity: number; // 溅落的透明度
}

export class RainEffect {
  private canvas: HTMLCanvasElement;
  private ctx: CanvasRenderingContext2D;
  private raindrops: RainDrop[] = []; // 存储雨滴的数组
  private splashes: SplashDrop[] = []; // 存储溅落效果的数组
  private isRaining: boolean = false; // 是否下雨
  private intensity: number = 1; // 雨的强度，1为正常，0-2之间调整
  private cameraOffsetX: number = 0; // 相机X轴偏移量
  private cameraOffsetY: number = 0; // 相机Y轴偏移量
  private windFactor: number = 0.2; // 风向因子，正值表示向右，负值表示向左
  private timeStore = useTimeStore();

  constructor() {
    this.canvas = document.createElement("canvas");
    const { width, height } = getScreenSize();
    this.canvas.width = width;
    this.canvas.height = height;
    this.canvas.style.position = "absolute";
    this.canvas.style.top = "0";
    this.canvas.style.left = "0";
    this.canvas.style.pointerEvents = "none";
    this.canvas.style.zIndex = "5";

    document.body.appendChild(this.canvas);

    this.ctx = this.canvas.getContext("2d")!;

    // 初始化雨滴
    // this.createRaindrops();
  }

  /**
   * 创建雨滴
   */
  private createRaindrops() {
    const { width, height } = getScreenSize();
    const raindropCount = Math.floor(100 * this.intensity); // 根据强度调整雨滴数量

    this.raindrops = [];
    for (let i = 0; i < raindropCount; i++) {
      const delay = Math.random() * 5000;

      setTimeout(() => {
        if (this.isRaining) {
          this.raindrops.push({
            x: Math.random() * width + this.cameraOffsetX * globalScale,
            y: -20 - Math.random() * height + this.cameraOffsetY * globalScale, // 从屏幕上方开始
            length: 10 + Math.random() * 20, // 雨滴长度
            speed: 15 + Math.random() * 10, // 雨滴速度
            opacity: 0.6 + Math.random() * 0.4, // 雨滴透明度
          });
        }
      }, delay);
    }
  }

  /**
   * 创建溅落效果
   * @param x 溅落的 x 坐标
   * @param y 溅落的 y 坐标
   */
  private createSplashdrops(x: number, y: number) {
    const maxRadius = 15 + Math.random() * 18;
    this.splashes.push({
      x,
      y,
      radius: 5,
      maxRadius,
      opacity: 0.8,
    });
  }

  /**
   * 开始下雨
   * @param intensity 雨的强度，1为正常，0-2之间调整
   */
  public startRain(intensity: number = 1) {
    this.isRaining = true;
    this.intensity = Math.max(0, Math.min(2, intensity)); // 限制强度在0-2之间
    this.windFactor = Math.random() * 0.8 - 0.4; // 随机风向
    this.createRaindrops();
    this.animate();
  }

  /**
   * 停止下雨
   */
  public stopRain() {
    this.isRaining = false;
  }

  /**
   * 更新相机位置
   */
  private updateCameraPostion() {
    const mapStore = useMapStore();
    const userStore = useUserStore();
    const { playerPosition } = storeToRefs(userStore);
    const { mapPixelWidth, mapPixelHeight } = storeToRefs(mapStore);

    // 计算相机的中心点
    const viewPortCenterX = this.canvas.width / 2 / globalScale;
    const viewPortCenterY = this.canvas.height / 2 / globalScale;

    // 计算最大滚动距离
    const maxScrollX = Math.max(
      0,
      mapPixelWidth.value - this.canvas.width / globalScale
    );
    const maxScrollY = Math.max(
      0,
      mapPixelHeight.value - this.canvas.height / globalScale
    );

    // 计算相机偏移量
    this.cameraOffsetX = Math.floor(
      Math.max(0, playerPosition.value.x - viewPortCenterX)
    );
    this.cameraOffsetX = Math.min(this.cameraOffsetX, maxScrollX);
    this.cameraOffsetY = Math.floor(
      Math.max(0, playerPosition.value.y - viewPortCenterY)
    );
    this.cameraOffsetY = Math.min(this.cameraOffsetY, maxScrollY);
  }

  /**
   * 更新雨滴位置
   */
  private updateRaindrops() {
    const { width, height } = getScreenSize();

    for (let i = 0; i < this.raindrops.length; i++) {
      const drop = this.raindrops[i];

      // 更新雨滴位置
      drop.y += drop.speed;
      drop.x += drop.speed * this.windFactor; // 模拟风的效果

      // 计算相对于视口的位置
      const relativeX = drop.x - this.cameraOffsetX * globalScale;
      const relativeY = drop.y - this.cameraOffsetY * globalScale;

      const disappearChance = Math.min(0.005 + (drop.y / height) * 0.03, 0.05);

      // 如果雨滴超出屏幕或随机消失
      if (
        relativeY > height ||
        relativeX < -50 ||
        relativeX > width + 50 ||
        Math.random() < disappearChance
      ) {
        if (
          relativeY < height &&
          relativeY > 0 &&
          relativeX > 0 &&
          relativeX < width
        ) {
          this.createSplashdrops(drop.x, drop.y);
        }

        // 从数组中移除雨滴
        this.raindrops.splice(i, 1);

        // 创建新的雨滴，保持雨滴总数不变
        if (this.isRaining) {
          this.raindrops.push({
            x: Math.random() * width + this.cameraOffsetX * globalScale,
            y: -20 - Math.random() * 50 + this.cameraOffsetY * globalScale,
            length: 10 + Math.random() * 20,
            speed: 15 + Math.random() * 10,
            opacity: 0.6 + Math.random() * 0.4,
          });
        }
      }
    }

    // 更新溅落效果
    for (let i = 0; i < this.splashes.length; i++) {
      const splash = this.splashes[i];
      splash.radius += 0.3;
      splash.opacity -= 0.03;

      // 如果溅落效果消失，从数组中移除
      if (splash.opacity <= 0 || splash.radius >= splash.maxRadius) {
        this.splashes.splice(i, 1);
      }
    }
  }

  /**
   * 绘制雨滴
   */
  private drawRainDrops() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    const timeBrightness = this.timeStore.brightnessFactor;

    this.ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"; // 设置线条颜色
    this.ctx.lineWidth = 2; // 设置线条宽度

    this.updateCameraPostion();

    // 绘制雨滴
    for (const drop of this.raindrops) {
      this.ctx.beginPath(); // 开始新的路径
      // 相机偏移量
      const drawX = drop.x - this.cameraOffsetX * globalScale;
      const drawY = drop.y - this.cameraOffsetY * globalScale;
      this.ctx.moveTo(drawX, drawY); // 移动到雨滴的起始位置
      const windTilt = this.windFactor * 8 * this.intensity;
      this.ctx.lineTo(drawX + windTilt, drawY + drop.length); // 绘制雨滴的线条
      this.ctx.globalAlpha = drop.opacity; // 设置透明度
      const finalOpacity = drop.opacity * timeBrightness;
      this.ctx.globalAlpha = finalOpacity;
      this.ctx.stroke(); // 绘制线条
    }

    // 绘制溅落效果
    this.ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
    for (const splash of this.splashes) {
      this.ctx.beginPath();
      this.ctx.save();
      this.ctx.scale(1.5, 0.7); // 横向拉伸
      // 相机偏移量
      const drawX = (splash.x - this.cameraOffsetX * globalScale) / 1.5;
      const drawY = (splash.y - this.cameraOffsetY * globalScale) / 0.7;
      this.ctx.arc(drawX, drawY, splash.radius, 0, Math.PI * 2); // 绘制圆形
      this.ctx.restore();
      const finalSplashOpacity = splash.opacity * timeBrightness;
      this.ctx.globalAlpha = finalSplashOpacity;
      this.ctx.fill();
    }

    this.ctx.globalAlpha = 1;
  }

  /**
   * 动画循环
   */
  private animate() {
    if (!this.isRaining) return;

    this.updateRaindrops();
    this.drawRainDrops();

    requestAnimationFrame(() => this.animate());
  }

  /**
   * 隐藏雨效果
   */
  public hideRainEffect() {
    if (this.canvas) {
      this.canvas.style.display = "none";
    }
  }

  /**
   * 显示雨效果
   */
  public showRainEffect() {
    if (this.canvas) {
      this.canvas.style.display = "block";

      if (!this.isRaining) {
        this.startRain(this.intensity);
      }
    }
  }

  /**
   * 清除雨滴效果
   */
  clear() {
    this.raindrops = [];
    if (this.ctx) {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
  }
}
